<?php

declare(strict_types=1);
namespace Service\StoreCardService;
use Service\BaseService;
use Service\Code\Normal;
use App\Model\BbcModel\StoreCard;
use function EasySwoole\Spl\trim;
use Hyperf\DbConnection\Db;
use App\Model\BbcModel\StoreCardLog;

/**
 * 储值卡服务中心
 * @author chenshubo
 */
class StoreCardService extends BaseService
{
    /**
     * 储值卡查询
     * @param int $cid
     * @param int $mn_sid
     * @param array $body
     * @return int[]|string[]|array[]
     */
    public function selectStoredCard(int $cid,int $mn_sid,array $body = [])
    {
        if(empty($body['number'])){
            return Normal::returnCode(Normal::FAIL, '储值卡号不能为空');
        }
        
        $storedcard= $this->queryStoredCard($cid, $mn_sid, $body['number']);
        if($storedcard){
            return Normal::returnCode(Normal::SUC, '成功', $storedcard);
        }
        return Normal::returnCode(Normal::FAIL, '查询结果为空');
    }
    
    /**
     * 验证储值卡支付密码
     * @param int $cid
     * @param int $mn_sid
     * @param array $body
     * @return int[]|string[]|array[]
     */
    public function checkStoredCardPayPassWord(int $cid,int $mn_sid,array $body = [])
    {
        if(empty($body['number'])){
            return Normal::returnCode(Normal::FAIL, '储值卡号不能为空');
        }
        
        if(empty($body['password'])){
            return Normal::returnCode(Normal::FAIL, '储值卡号密码不能为空');
        }
        
        if(empty($body['money'])){
            return Normal::returnCode(Normal::FAIL, '储值卡号金额不能为空');
        }
        
        $number = $body['number'];
        $storecard = $this->queryStoredCard($cid,$mn_sid, $body['number']);
        if( empty($storecard) ) {
            return Normal::returnCode(Normal::FAIL, '储值卡不存在');
        }
        
        if( $storecard['status'] == 0 ){
            return Normal::returnCode(Normal::FAIL, '储值卡未激活');
        }
        
        if( md5($body['password']) != $storecard['password'] ) {
            return Normal::returnCode(Normal::FAIL, '储值卡密码错误');
        }
        
        if( bccomp($storecard['money'], $money,2) == -1 ) {
            return Normal::returnCode(Normal::FAIL, '储值卡金额不足');
        }
        
        return Normal::returnCode(Normal::SUC, '验证通过',[
            'money' => $storecard['money'],
            'id'    => $storecard['id']
        ]);
    }
    
    /**
     * 验证储值卡获取
     * @param int $cid
     * @param int $mn_sid
     * @param string $number
     */
    public function queryStoredCard(int $cid,int $mn_sid,string $number)
    {
        return StoreCard::instance()->info(['cid'=>$cid,'mn_sid'=>$mn_sid,'number'=> \trim($number)]);
    }
    
    
    /**
     * 批量获取储值卡集合
     * @param array $ids
     */
    public function queryStoredCardByIds(array $ids = [] )
    {
        if( empty($ids)  ) {
            return [];
        }
        
        return StoreCard::instance()
        ->select([
            'id',
            'number'
        ])
        ->whereIn('id',$ids)
        ->get()
        ->toArray();
        
        return StoreCard::instance()->info(['cid'=>$cid,'mn_sid'=>$mn_sid,'number'=> \trim($number)]);
    }
    
    /**
     * 检查储值卡余额是否足够
     * @param int $cid
     * @param int $mn_sid
     * @param string $number
     * @param string $password
     * @param string $money
     * @return mixed
     */
    public function checkStoredCard(int $cid ,int $mn_sid ,string $number ,string $password = null,string $money = '0.00')
    {
        $password   = isset($param['password'])?$param['password']:0;
        $money      = isset($param['money'])?$param['money']:0;
        $storecard  = $this->info(['cid'=>$cid,'mn_sid'=>$mn_sid,'number'=>$number]);
        if( empty($storecard) ) {
            return Normal::returnCode(Normal::FAIL, '储值卡不存在');
        }
        
        if( $storecard['status'] == 0 ) {
            return Normal::returnCode(Normal::FAIL, '储值卡未激活');
        }
        
        if( md5($password) != $storecard['password'] ) {
            return Normal::returnCode(Normal::FAIL, '储值卡密码错误');
        }
        
        if( bccomp($storecard['money'],$money,2) == -1 ) {
            return Normal::returnCode(Normal::FAIL, '储值卡金额不足');
        }

        return Normal::returnCode(Normal::SUC, '验证通过',[
            'money' => $storecard['money'],
            'id'    => $storecard['id']
        ]);
    }
    
    /**
     * 储值卡余额扣除
     * @param int $store_card_id
     * @param string $store_card_money
     * @param array $extra
     * @return mixed
     */
    public function userStoreCardConsumer(int $store_card_id,string $store_card_money,array $extra = [])
    {
        $storeCard = StoreCard::instance()->info(['id'=>$store_card_id]);
        if(empty($storeCard)){
            return Normal::returnCode(Normal::FAIL, '储值卡信息未查到');
        }
        
        $update_result = Storecard::instance()->where(['id'=>$store_card_id])->update([
            'money'         => Db::raw("money-{$store_card_money}"),
            'money_use'     => Db::raw("money_use+{$store_card_money}"),
        ]);
        if(!$update_result){
            return Normal::returnCode(Normal::FAIL, '储值卡余额扣款失败');
        }
        
        $storeCardLogData = [
            'cid'           => $extra['cid'],
            'mn_sid'        => $extra['mn_sid'],
            'order_number'  => $extra['order_sn'],
            'type'          => 0,
            'money'         => $store_card_money,
            'after_money'   => bcsub((string)$storeCard['money'],(string)$store_card_money,2),
            'before_money'  => $storeCard['money'],
            'storecard_id'  => $store_card_id,
            'cd'            => time()
        ];
        
        $log_result = StoreCardLog::instance()->add($storeCardLogData);
        if(!$log_result){
            return Normal::returnCode(Normal::FAIL, '储值卡变动记录写入失败');
        }
        
        return Normal::returnCode(Normal::SUC, '操作完成');
    }
    
    /**
     * 储值卡消费金额返还
     * @param int $store_card_id
     * @param string $store_card_money
     * @param array $extra
     * @return type
     */
     public function userStoreCardReBack(int $store_card_id,string $store_card_money,array $extra = []){
        $storeCard = StoreCard::instance()->info(['id'=>$store_card_id]);
        if(empty($storeCard)){
            return Normal::returnCode(Normal::FAIL, '储值卡信息未查到');
        }
        $update_result = Storecard::instance()->where(['id'=>$store_card_id])->update([
            'money'         => Db::raw("money+{$store_card_money}"),
            'money_use'     => Db::raw("money_use-{$store_card_money}"),
        ]);
        if(!$update_result){
            return Normal::returnCode(Normal::FAIL, '储值卡余额返还失败');
        }
        
        $storeCardLogData = [
            'cid'           => $extra['cid'],
            'mn_sid'        => $extra['mn_sid'],
            'order_number'  => $extra['sale_sn'],
            'type'          => 1,
            'money'         => $store_card_money,
            'after_money'   => bcsub((string)$storeCard['money'],(string)$store_card_money,2),
            'before_money'  => $storeCard['money'],
            'storecard_id'  => $store_card_id,
            'cd'            => time()
        ];
        
        $log_result = StoreCardLog::instance()->add($storeCardLogData);
        if(!$log_result){
            return Normal::returnCode(Normal::FAIL, '储值卡变动记录写入失败');
        }
        return Normal::returnCode(Normal::SUC, '操作完成');
     }
}